package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.supplier.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SearchAcceptActivity extends BaseActivity {

    private View vSearch;
    private TextView tvSearch;
    private EditText etContent;
    ListView lvHistory;
    List<String> historyList = new ArrayList<String>();
    StringAdapter historyAdapter;
    String historyTogether;

    @Override
    protected View getToolBar() {
        View actionbar = this.inflaterView(R.layout.toolbar_search, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);


        this.ivBack = actionbar.findViewById(R.id.iv_back);

        this.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        vSearch = actionbar.findViewById(R.id.ll_search);
        tvSearch = actionbar.findViewById(R.id.tv_search);
        etContent = actionbar.findViewById(R.id.et_content);

        etContent.setHint("请输入商品名称");
        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    if (TextUtils.isEmpty(etContent.getText().toString())) {
                        return true;
                    }
                    onSearch();
                    return true;
                }
                return false;
            }
        });
        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onSearch();
            }
        });

        return actionbar;
    }

    private void onSearch() {
        putHistoryTogether();

        String keywords = etContent.getText().toString();

        if (keywords == null || "".equals(keywords.trim())){
            return;
        }


        Intent intent = new Intent(this,BaseStoreSearchResultActivity.class);
        intent.putExtra("keywords",keywords);
        intent.putExtra("mHasAgent",getIntent().getBooleanExtra("mHasAgent",true));
        intent.putExtra("baseStoreId",getIntent().getStringExtra("baseStoreId"));
        startActivityForResult(intent,0x1991);

    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null){
            getIntent().putExtra("baseStoreId",savedInstanceState.getString("baseStoreId"));
        }
        setContentView(R.layout.activity_search_accept);
        initView();


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("baseStoreId",getIntent().getStringExtra("baseStoreId"));
        super.onSaveInstanceState(outState);
    }

    void initView() {
        lvHistory = (ListView) findViewById(R.id.lv_history);
        findViewById(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                builder.setMessage("确定要删除历史搜索吗？");//设置显示的内容
                //builder.setTitle("提示");
                builder.setTitleVisible(false);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        SharedPreferences sp = getSharedPreferences("search_history", Context.MODE_PRIVATE); //私有数据
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("base_store_product_history"+ BaseApplication.getInstance().getUser().getAccountId()+"_"+BaseApplication.getInstance().getMerchantId(), "");
                        editor.commit();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件
                        dialog.dismiss();
                    }

                });
                builder.create().show();
            }
        });

        historyAdapter = new StringAdapter(this, historyList, R.layout.item_string);
        lvHistory.setAdapter(historyAdapter);

        historyTogether = getHistoryTogether();
        reqSearchHistory(historyTogether);
    }

    String getHistoryTogether() {
        SharedPreferences sp = getSharedPreferences("search_history", Context.MODE_PRIVATE); //私有数据
        return sp.getString("base_store_product_history"+ BaseApplication.getInstance().getUser().getAccountId()+"_"+BaseApplication.getInstance().getMerchantId(), "");
    }

    void putHistoryTogether() {
        SharedPreferences sp = getSharedPreferences("search_history", Context.MODE_PRIVATE); //私有数据
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("base_store_product_history"+ BaseApplication.getInstance().getUser().getAccountId()+"_"+BaseApplication.getInstance().getMerchantId(), sp.getString("base_store_product_history"+ BaseApplication.getInstance().getUser().getAccountId()+"_"+BaseApplication.getInstance().getMerchantId(), "") + "," + etContent.getText().toString().trim());
        editor.commit();
    }

    void reqSearchHistory(String historyTogether) {


        historyList.clear();
        if (!historyTogether.equals("")) {
            ArrayList<String> flag = new ArrayList<>();
            flag.addAll(Arrays.asList(historyTogether.split(",")));
            for (int i = flag.size() - 1; i > 0; i--) {
                if (!historyList.contains(flag.get(i)))
                    historyList.add(flag.get(i));
                if (historyList.size() == 10)
                    break;
            }
        }
        historyAdapter.notifyDataSetChanged();

    }


    class StringAdapter extends CommonAdapter<String> {
        public StringAdapter(Context context, List<String> historyList, int a) {
            super(context, historyList, a);
        }

        @Override
        public void convert(ViewHolder holder, final String bean) {
            holder.setText(R.id.tv_string, bean);
            holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etContent.setText(bean);
                    etContent.setSelection(bean.length());
                    tvSearch.performClick();
                }
            });
        }
    }

}
